<template>
    <section class="">

        <el-form :inline="true" :model="formSearch" class="form_inline form_bacolor form_div">
            <el-form-item label="品牌名称" size="small">
                <el-input v-model="formSearch.name" placeholder="请输入品牌名称"></el-input>
            </el-form-item>
            <el-form-item size="small">
                <el-button size="small" type="primary" @click="getlist">搜 索</el-button>
                <el-button size="small" @click="add">添 加</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="name" label="品牌名称">
            </el-table-column>
            <el-table-column prop="" label="状态">
                <template slot-scope="scope">
                    <span v-if="scope.row.enable == true" style="color: #52c41a;">启用</span>
                    <span v-if="scope.row.enable == false" style="color: rgb(255, 0, 0);">禁用</span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button v-if="" type="text" size="small " @click="xiugaiorxq(scope.row,2)">编辑</el-button>
                    <el-button size="small " type="text" @click="IsActive(scope.row)">
                        {{scope.row.enable==true?'禁用':'启用'}}</el-button>
                    <el-button size="small " type="text" @click="deleInfor(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <paging @changePage=handleCurrentPage :get-total='total'></paging>

        <el-dialog :title="addorupdata==1?'新增':addorupdata==2?'修改':'详情'" width="30%" :visible.sync="addFormVisible"
            @closed='closeadd' :close-on-click-modal="false">
            <el-form :model="addForm" label-width="120px" ref="addform" :disabled="disabled">

                <el-form-item label="品牌名称" size="small" prop="name"
                    :rules="{ required: true, message: '该项不能为空', trigger: 'change' }">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="是否启用" size="small" prop="enable"
                    :rules="{ required: true, message: '该项不能为空', trigger: 'change' }">
                    <el-switch v-model="addForm.enable" active-color="#13ce66" inactive-color="#ff4949" active-text="是"
                        inactive-text="否" :inactive-value=false :active-value=true>
                    </el-switch>
                </el-form-item>
                <el-form-item label="图标：" prop="">
                    <el-upload ref="addupload" :auto-upload="false" class="avatar-uploader" :show-file-list="false"
                        :action="uploadPath" list-type="picture" :on-change="onChange"
                        :on-success="handleAvatarSuccess">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="closeadd">取消</el-button>
                <el-button v-if="addorupdata!=3" type="primary" @click.native="addlist">提交</el-button>
            </div>
        </el-dialog>
        <!-- 二维码 -->
        <el-dialog title="设备二维码" :visible.sync="codeShow" width="25%" :close-on-click-modal="false">
            <div class="shouquan" id='printBill' ref="shouquan1">
                <div>设备名称：{{ewmwz.name}}</div>
                <div class="codediv">
                    <div class="qrcode" ref="qrCodeUrl"></div>
                </div>
                <!-- <div>位置：{{ewmwz.sectionName}}{{ewmwz.houseName==null?'':'-'+ewmwz.houseName}}</div> -->
                <div>扫码获取设备详细信息</div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="medium " @click="codeShow = false">关 闭</el-button>
                <el-button size="medium " @click="printContext">打印</el-button>
                <!-- updataImg(1) -->
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import QRCode from "qrcodejs2";
    import print from 'print-js'
    import paging from "../paging"
    import { dictionaryProfile, xqSelectList, sectionTree, brandLibraryInsert, brandLibraryUpdate, brandLibraryDelete, brandLibraryList, listSelect, sectionList, systemList } from '../../url/api'
    export default {
        data() {
            return {
                uploadPath: '/api/v1.0/file/upload/file',
                defaultProps2: {
                    children: 'children',
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    expandTrigger: 'hover', checkStrictly: true
                },
                profilelist: [],
                sectionTree: [],
                tableData: [],
                formSearch: {
                    current: 1,
                    size: 10
                },
                productdata: {},
                addorupdata: 1,
                xqTree: [],
                addForm: {
                    icon: '',
                },
                total: 0,//数据总数
                addFormVisible: false,
                addorupdata: 1,
                disabled: false,
                rowid: '',
                productlist: [],
                addsectionList: [],
                subsystemList: [],
                imgfileList: [],
                imageUrl: "",
                codeShow: false,
                ewmwz: {},
            }
        },

        methods: {
            // ============设备二维码===========
            sbcode(id, row) {
                // //console.log(id);
                let text = '' + id;
                this.ewmwz = row;
                this.codeShow = true;
                setTimeout(() => {
                    this.creatQrCode(text);
                }, 100)

            },
            creatQrCode(text) {
                // //console.log(text);
                if (this.qrcode) {
                    this.qrcode.clear(); // 清除代码
                    this.qrcode.makeCode(text); // 生成另外一个二维码
                    return
                }
                this.qrcode = new QRCode(this.$refs.qrCodeUrl, {
                    text: text,
                    width: 150,
                    height: 150,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.H
                })
            },
            //打印
            printContext() {
                const style = '@media print { .shouquan{ text-align: center;color: black;background: #fff;margin-left:20%} .codediv {margin: 20px 0;text-align: center; } ';

                printJS({
                    printable: 'printBill', //shouquan打印区域
                    type: 'html',  //打印类型html，还可以是json，image等，详细写法见官网
                    //targetStyles: ['*'],  //css样式，写成*代表打印样式完全继承你页面的样式
                    style: style
                    //  maxWidth:'800px'  //打印界面最大宽度，适当调整可以解决打印页面过宽，显示不完整的问题
                })
            },
            //=============设备二维码end========
            handleAvatarSuccess(resp, file, fileList) {
                debugger
                if (resp.ok) {
                    this.imgfileList = fileList
                    // console.log(resp.data[0], "QQQQQQQQQQ");
                    this.addForm.icon = resp.data[0];
                    this.imageUrl = resp.data[0];
                    this.gotoadd()
                }

            },
            gotoadd() {
                if (this.addorupdata == 1) {
                    brandLibraryInsert(this.addForm).then((res) => {
                        console.log("新增", res)
                        if (res.data.ok) {
                            this.$message({
                                message: '添加成功',
                                type: 'success'
                            });
                            this.getlist()
                        } else {
                            this.$message('添加失败')
                        }
                        this.closeadd()
                    })
                } else if (this.addorupdata == 2) {

                    brandLibraryUpdate(this.addForm).then((res) => {
                        if (res.data.ok) {
                            this.$message({
                                message: '修改成功',
                                type: 'success'
                            });
                            this.getlist()
                        } else {
                            this.$message('修改失败')
                        }
                        this.closeadd()
                    })
                }
            },
            onChange(file, fileList) {
                console.log(file, fileList, "aaaaaaaaaaa");
                this.imgfileList = fileList;
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            handleChange(value) {
                // this.addForm.sectionId = this.option1[this.option1.length - 1];
                console.log("区域ID", this.addForm.sectionId);
            },
            handleCurrentPage(val) {//页码改变
                this.formSearch.current = val
                this.getlist()
            },
            getsubsystemList() {
                this.subsystemList = [];
                // debugger
                systemList({}).then(res => {

                    console.log(res);
                    this.subsystemList = res.data.data
                })
            },
            deleInfor(id) {
                let arrId = {}
                if (id) {
                    arrId.brandId =id;
                }
                
                this.$confirm("确定删除吗？", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    brandLibraryDelete(arrId).then((res) => {
                        console.log("删除", res)
                        if (res.data.ok) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getlist()
                        } else {
                            this.$message('删除失败')
                        }
                    })

                }).catch(() => {

                });
            },
            xiugaiorxq(row, index) {
                this.addorupdata = index
                if (index == 3) {
                    this.disabled = true
                }
                this.rowid = row.id
                this.addForm = {
                    id: row.id,
                    name: row.name,
                    enable: row.enable,
                    icon: row.icon,
                },
                    this.imageUrl = row.icon

                this.addFormVisible = true;
            },
            IsActive(row) {
                let params = {
                    id: row.id,
                    name: row.name,
                    icon: row.icon,
                    enable: row.enable == true ? false : true,
                }
                this.$confirm("确定执行此操作吗？", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    brandLibraryUpdate(params).then((res) => {
                        if (res.data.ok) {
                            this.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            this.getlist()
                        } else {
                            this.$message('操作失败')
                        }
                        this.closeadd();
                    })
                })
            },
            addlist() {
                // console.log("this.addF", this.addForm)
                this.$refs.addform.validate((valid) => {
                    // console.log("valid", valid)
                    if (valid) {
                        // this.addForm.deviceId = this.productdata.id;
                        // this.addForm.deviceType = 'product';
                        // delete this.addForm.projectId
                        this.$confirm("确定执行此操作吗？", '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            // this.adddialog = false
                            // debugger
                            // console.log(this.addForm)
                            console.log(this.imgfileList.length, this.imageUrl, this.addForm.icon);
                            if (this.imgfileList.length == 0 && this.imageUrl == this.addForm.icon) {
                                this.gotoadd();
                            } else {
                                // this.addForm.picture = ''
                                // this.pictrueNum = 0
                                this.$refs.addupload.submit();
                            }

                            // if (this.addorupdata == 1) {
                            //     brandLibraryInsert(this.addForm).then((res) => {
                            //         console.log("新增", res)
                            //         if (res.data.ok) {
                            //             this.$message({
                            //                 message: '添加成功',
                            //                 type: 'success'
                            //             });
                            //             this.getlist()
                            //         } else {
                            //             this.$message('添加失败')
                            //         }
                            //         this.closeadd()
                            //     })
                            // } else if (this.addorupdata == 2) {

                            //     brandLibraryUpdate(this.addForm).then((res) => {
                            //         if (res.data.ok) {
                            //             this.$message({
                            //                 message: '修改成功',
                            //                 type: 'success'
                            //             });
                            //             this.getlist()
                            //         } else {
                            //             this.$message('修改失败')
                            //         }
                            //         this.closeadd()
                            //     })
                            // }
                            this.adddialog = false

                        })

                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            closeadd() {
                this.addForm = {
                    // deviceId: this.productdata.id,
                    // deviceType: 'product',
                    // name: '',
                    // pointRef: '',
                    // readOnly: 1,
                    // sn: '',
                    // unit: '',
                    // valueType: ''
                    icon: '',
                },
                    this.imgfileList = []
                this.imageUrl = ''
                this.$refs.addform.resetFields();
                this.addorupdata = 1
                this.addFormVisible = false;
                this.disabled = false
            },
            add() {
                this.addFormVisible = true;
                this.addorupdata = 1;
            },
            getlist() {
                // console.log(this.productdata,"QQQQQQQQ");
                let params = this.formSearch;
                brandLibraryList(params).then((res) => {//
                    console.log(res)
                    if (res.data.data) {
                        this.tableData = res.data.data.records;
                        this.total = res.data.data.total * 1
                    }
                })
                xqSelectList({}).then((res) => {
                    //项目选择列表
                    console.log(res);
                    if (res.data.ok) {
                        this.xqTree = res.data.data;
                        // this.formSearch.projectId = this.xqTree[0].id;
                        // this.getlist();
                    }
                });
                // console.log("AAAAAAAAAAAAAAA",this);
            },

            goprojectIdselect(projectId) {
                // debugger
                let params = {
                    projectId: projectId * 1  //
                }
                params = JSON.parse(JSON.stringify(params));
                listSelect(params).then(res => {
                    console.log(res);
                    this.productlist = res.data.data;
                    console.log(this.productlist);
                })
            },
            getdictionaryProfile() {
                dictionaryProfile().then(res => {
                    console.log(res);
                    this.profilelist = res.data.data;
                    console.log(this.profilelist);
                })
            }
        },

        mounted() {
            this.getlist()
            this.getsubsystemList()
            this.getdictionaryProfile();
            console.log(this.$route.query, "路由跳转参数！11111");
            if (this.$route.query && this.$route.query.invoiceresource) {
                if (this.$route.query.invoiceresource == 'add') {
                    this.add()
                }
            }
        },
        components: {
            paging
        },
        // watch: {
        //     // "$route"(val) {
        //     //     debugger
        //     //     console.log(val,"路由跳转参数！");
        //     //     if(this.$route.query && this.$route.query.resource == "add"){
        //     //        this.add()
        //     //     }
        //     // }
        // }


    }
</script>
<style>
    .label_letter {
        font-size: 16px;
        margin-bottom: 10px;
    }

    .label_text {
        font-size: 18px;
    }

    .head_div {
        margin-bottom: 20px;
    }

    .form_div {
        padding-bottom: 20px;
        padding-left: 20px;
    }

    .codediv {
        margin: 20px 0;
        text-align: center;
    }

    .shouquan {
        text-align: center;
        color: black;
        background: #fff;
        padding: 50px 0;
    }

    .qrcode {
        display: inline-block;
    }
</style>